<?php
/**
 * 库存总表(站点)
 * User: bgl
 * Date: 2023/7/11
 * Time: 15:22
 */

namespace App\Admin\Controllers\Inventory;


use App\Models\Basics\SysArea;
use App\Models\Inventory\InventoryTotalArea;
use App\Models\Product\ProductClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class InventoryTotalAreaController extends AdminController{

    protected $title = '库存总表（站点）';

    protected $filters = [
        'sku' => null,
        'area_id' => null,
        'classify_id' => null,
    ];

    protected function grid(){

        $filtersField = array_keys($this->filters);
        $action = getAction($filtersField);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);

        $total = $query->get()->toArray();
        $totalArr['total_cn_instant'] = array_sum(array_column($total, 'cn_instant'));
        $totalArr['total_cn_transit'] = array_sum(array_column($total, 'cn_transit'));
        $totalArr['total_cn_reserve'] = array_sum(array_column($total, 'cn_reserve'));

        $totalArr['total_fba_instant'] = array_sum(array_column($total, 'fba_instant'));
        $totalArr['total_fba_transit'] = array_sum(array_column($total, 'fba_transit'));

        $totalArr['total_os_box_instant'] = array_sum(array_column($total, 'os_box_instant'));
        $totalArr['total_os_box_transit'] = array_sum(array_column($total, 'os_box_transit'));
        $totalArr['total_os_box_reserve'] = array_sum(array_column($total, 'os_box_reserve'));

        $totalArr['total_os_removale_instant'] = array_sum(array_column($total, 'os_removale_instant'));
        $totalArr['total_os_removale_transit'] = array_sum(array_column($total, 'os_removale_transit'));
        $totalArr['total_os_removale_reserve'] = array_sum(array_column($total, 'os_removale_reserve'));

        $totalArr['total_os_dropshipping_instant'] = array_sum(array_column($total, 'os_dropshipping_instant'));
        $totalArr['total_os_dropshipping_transit'] = array_sum(array_column($total, 'os_dropshipping_transit'));
        $totalArr['total_os_dropshipping_reserve'] = array_sum(array_column($total, 'os_dropshipping_reserve'));

        $totalArr['total_os_instant'] = (array_sum(array_column($total, 'os_box_instant'))) + (array_sum(array_column($total, 'os_removale_instant'))) + (array_sum(array_column($total, 'os_dropshipping_instant')));
        $totalArr['total_os_transit'] = (array_sum(array_column($total, 'os_box_transit'))) + (array_sum(array_column($total, 'os_removale_transit'))) + (array_sum(array_column($total, 'os_dropshipping_transit')));
        $totalArr['total_os_reserve'] = (array_sum(array_column($total, 'os_box_reserve'))) + (array_sum(array_column($total, 'os_removale_reserve'))) + (array_sum(array_column($total, 'os_dropshipping_reserve')));

        $paginator = $this->_paginator($query);

        $filtersBlade = [];
        $filtersBlade['sku'] = $this->filters['sku'];
        $filtersBlade['area_id'] = getOptions(SysArea::options(),$this->filters['area_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        $downloadUrl = '/xqc/inventory/inventory-area-download?' . http_build_query(array_merge(Request::all(),['_export_' => true]));
        return view('inventory.inventory-area.index', compact('paginator','totalArr', 'filtersBlade','action','downloadUrl'));
    }

    private function _getFilters($filtersField){
        $filters = [];
        foreach ($filtersField as $field){
            $filters[$field] = request($field);
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function _initQuery($filters){

        $query = InventoryTotalArea::query()->orderByDesc('id');

        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'sku'){
                $query->whereHas('sku', function ($query) use($filter){
                    $query->where('psku_code', 'like', "%{$filter}%")
                        ->orWhere('psku_cn', 'like', "%{$filter}%");
                });
            }
            if($field == 'classify_id'){
                $query->where('classify_id', $filter);
            }
            if($field == 'area_id'){
                $query->where('area_id', $filter);
            }
            if(in_array($field,['classify_id','area_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function download(){
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = [
            '站点','SKU编码','SKU名称','品类',
            'PUBLIC在库','PUBLIC在途','PUBLIC保留',
            '国内在库','国内在途','国内保留',
            'FBA在库','FBA在途',
            '海外仓在库(总计)','海外仓在途(总计)','海外仓保留(总计)',
            '海外仓在库(中转)','海外仓在途(中转)','海外仓保留(中转)',
            '海外仓在库(移库)','海外仓在途(移库)','海外仓保留(移库)',
            '海外仓在库(代发)','海外仓在途(代发)','海外仓保留(代发)'
        ];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="库存总表（站点）.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(800, function ($re) use ($fp){
                $data = InventoryTotalArea::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

}
